package com.timi_licai.timi_licai_account.fragment;


import android.animation.AnimatorInflater;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.timi_licai.timi_licai_account.MyConstants;
import com.timi_licai.timi_licai_account.R;
import com.timi_licai.timi_licai_account.database.DatabaseUtils;
import com.timi_licai.timi_licai_account.listener.OnPiegraphItemSelectedListener;
import com.timi_licai.timi_licai_account.utils.ScreenUtil;
import com.timi_licai.timi_licai_account.view.PiegraphView;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class CircleBookFragment extends Fragment implements View.OnClickListener {
    private PiegraphView view;
    private TextView text;
    private float radius;
    private int strokeWidth;
    private String strokeColor = "#BA999999";
    private float animSpeed = (float) 20;
    private String txtInfo = "";
    private Double[] items;
    private List<String> itemsName;
    private double sumOut = 0;
    private double sumIn = 0;
    private static int recodePosition = 0;
    private TextView txtItemsName;
    private TextView txtTotalItem;
    private TextView txtSumOut;
    private TextView txtSumIn;
    private TextView txtSumTotal;
    private int account;
    private ImageView imgRotate;

    public CircleBookFragment () {
    }

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSelectedBook();
    }

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container,
                              Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_circle_book, container, false);
        view = (PiegraphView) ret.findViewById(R.id.piechar_view);
        text = (TextView) ret.findViewById(R.id.content);
        txtTotalItem = (TextView) ret.findViewById(R.id.circle_book_totalItem);
        txtItemsName = (TextView) ret.findViewById(R.id.circle_book_pieInfo);
        txtSumOut = (TextView) ret.findViewById(R.id.circle_book_sumOut);
        txtSumIn = (TextView) ret.findViewById(R.id.circle_book_sumIn);
        txtSumTotal = (TextView) ret.findViewById(R.id.circle_book_sumTotal);
        ImageView imgFlag = (ImageView) ret.findViewById(R.id.circle_book_flag_btn);
        imgRotate = (ImageView) ret.findViewById(R.id.circle_book_rotate_btn);
        imgFlag.setOnClickListener(this);
        imgRotate.setOnClickListener(this);
        runCircle();
        view.setShowItem(0, true);
        return ret;
    }

    /**
     * 显示自定义控件
     */
    private void runCircle () {
        for (Double item : items) {
            sumOut += item;
        }
        txtInfo = (int) (items[0] / sumOut * 100) + "%";
        text.setText(txtInfo);
        radius = ScreenUtil.dip2px(getActivity(), 140);
        strokeWidth = ScreenUtil.dip2px(getActivity(), 3);
        view.setitemsValues(items);
        view.setStrokeColor(strokeColor);// 设置边缘的圆环颜色
        view.setItemSelectedListener(new OnPiegraphItemSelectedListener() {
            @Override
            public void onPieChartItemSelected (int position, String colorRgb,
                                                double size, float rate, float rotateTime) {
                txtInfo = (int) (items[position] / sumOut * 100) + "%";
                text.setText(txtInfo);
                txtItemsName.setText(itemsName.get(position).toString());
                txtTotalItem.setText(account + "笔");
                txtSumOut.setText("" + sumOut);
                txtSumIn.setText("" + sumIn);
                txtSumTotal.setText("" + (sumIn - sumOut));
            }
        });
    }

    /**
     * TODO 小图片响应事件，点击进入详情页面
     *
     * @param v
     */
    @Override
    public void onClick (View v) {
        int id = v.getId();
        switch (id) {
            case R.id.circle_book_flag_btn:
                break;
            case R.id.circle_book_rotate_btn:
                Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.circle_rote_btn);
                imgRotate.startAnimation(animation);
                view.setShowItem(recodePosition, true);
                recodePosition = recodePosition % (items.length);
                recodePosition++;
                if (recodePosition == (items.length)) {
                    recodePosition = 0;
                }
                break;
        }
    }

    /**
     * 获取选中账本id
     */
    private void getSelectedBook () {
        int bookId = 0;
        Cursor cursor = DatabaseUtils.query(MyConstants.TABLE_ACCOUNT_BOOK, null,
                "ismark=?", new String[] {"1"},
                null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                bookId = cursor.getInt(cursor.getColumnIndex("_id"));
            }
            cursor.close();
        }
        getAllOutDetails(bookId);
        getAllInDetails(bookId);
    }

    /**
     * 获取选中账本的支出所有信息
     */
    private void getAllOutDetails (int bookId) {
        if (bookId != 0) {
            List<Integer> data = new ArrayList<>();
            Cursor cursor = DatabaseUtils.query(MyConstants.TABLE_ACCOUNT_BOOK_DETAILS, null,
                    "bookid=? and io_choose=?", new String[] {bookId + "", "0"},
                    null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    int typeId = cursor.getInt(cursor.getColumnIndex("type_id"));
                    boolean judge = typeIdJudgeEqual(data, typeId);
                    if (judge == true) {
                        data.add(typeId);
                    }
                    account++;
                }
                cursor.close();
            }
            items = getDataByTypeId(data);
            itemsName = getTypeName(data);
        } else {
            items = new Double[] {0d};
            itemsName = new ArrayList<>();
            itemsName.add("一般");
        }
    }

    /**
     * 获取收入的所有信息
     *
     * @param bookId
     */
    private void getAllInDetails (int bookId) {
        if (bookId != 0) {
            List<Integer> data = new ArrayList<>();
            Cursor cursor = DatabaseUtils.query(MyConstants.TABLE_ACCOUNT_BOOK_DETAILS, null,
                    "bookid=? and io_choose=?", new String[] {bookId + "", "1"},
                    null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    int typeId = cursor.getInt(cursor.getColumnIndex("type_id"));
                    boolean judge = typeIdJudgeEqual(data, typeId);
                    if (judge == true) {
                        data.add(typeId);
                    }
                }
                cursor.close();
            }
            sumIn = getInByTypeId(data);
        } else {
            sumIn = 0;
        }
    }

    /**
     * 获取收入金额
     *
     * @param data
     * @return
     */
    private float getInByTypeId (List<Integer> data) {
        float result = 0;
        if (data.size() > 0) {
            Double[] sumFree = new Double[data.size()];
            // 为数组初始化
            for (int i = 0; i < data.size(); i++) {
                sumFree[i] = 0.0d;
            }
            for (int i = 0; i < data.size(); i++) {
                Cursor cursor = DatabaseUtils.query(MyConstants.TABLE_ACCOUNT_BOOK_DETAILS, null,
                        "type_id=?", new String[] {data.get(i) + ""},
                        null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        float free = cursor.getFloat(cursor.getColumnIndex("fee"));
                        sumFree[i] = sumFree[i] + free;
                    }
                    cursor.close();
                }
            }
            for (int i = 0; i < sumFree.length; i++) {
                result += sumFree[i];
            }
            return result;
        } else {
            return result;
        }
    }

    /**
     * 判断是否为相同 type_id
     *
     * @param list
     * @param flag
     * @return
     */
    private boolean typeIdJudgeEqual (List<Integer> list, int flag) {
        boolean judge = true;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) == flag) {
                judge = false;
                break;
            }
        }
        return judge;
    }

    /**
     * 根据type_id获取id相同的值，并计算其中free的和
     */
    private Double[] getDataByTypeId (List<Integer> data) {
        if (data.size() > 0) {
            Double[] sumFree = new Double[data.size()];
            // 为数组初始化
            for (int i = 0; i < data.size(); i++) {
                sumFree[i] = 0.0d;
            }
            for (int i = 0; i < data.size(); i++) {
                Cursor cursor = DatabaseUtils.query(MyConstants.TABLE_ACCOUNT_BOOK_DETAILS, null,
                        "type_id=?", new String[] {data.get(i) + ""},
                        null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        float free = cursor.getFloat(cursor.getColumnIndex("fee"));
                        sumFree[i] = sumFree[i] + free;
                    }
                    cursor.close();
                }
            }
            return sumFree;
        } else {
            return new Double[] {0d};
        }
    }

    /**
     * 根据类型id，获取相应类型名称
     *
     * @param data
     * @return
     */
    private List<String> getTypeName (List<Integer> data) {
        List<String> typeName = new ArrayList<>();
        if (data.size() > 0) {
            String flagStr = "";
            for (int i = 0; i < data.size(); i++) {
                Cursor cursorName = DatabaseUtils.query(MyConstants.TABLE_CONSUME_TYPE, null,
                        "_id=?", new String[] {data.get(i) + ""},
                        null);
                if (cursorName != null) {
                        while (cursorName.moveToNext()) {
                            String typename = cursorName.getString(cursorName.getColumnIndex("typename"));
                            if (!typename.equals(flagStr)) {
                                typeName.add(typename);
                                flagStr = typename;
                            }
                        }
                        cursorName.close();
                }
            }
            return typeName;
        } else {
            typeName.add("一般");
            return typeName;
        }
    }

    @Override
    public void onResume () {
        super.onResume();
        account = 0;
        getSelectedBook();
        sumOut = 0;
        sumIn = 0;
        runCircle();
    }

    @Override
    public void onPause () {
        super.onPause();
        account = 0;
        getSelectedBook();
    }

    @Override
    public void onDestroy () {
        super.onDestroy();
        sumOut = 0;
        sumIn = 0;
        account = 0;
    }
}
